package com.zhugang.week13.linkedlist;

import com.zhugang.week13.stack.Stack;

/**
 * @program algorithms
 * @description: isPalindrome
 * @author: chanzhugang
 * @create: 2022/10/23 22:17
 */
public class IsPalindrome {

    /**
     * 234 回文链表
     * https://leetcode.cn/problems/palindrome-linked-list/
     *
     * @param head
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        // 经典： 找中间节点，翻转后半部分链表和前半分链表是否相等

        // 快慢指针找中间节点
        ListNode middleNode = findMiddleNode(head);
        // 翻转后半部分链表
        ListNode rightNode = reverseRightNode(middleNode.next);
        ListNode p = head;
        ListNode q = rightNode;
        // 比较前半部分链表和翻转的后半部分链表
        while (q != null) {
            if (p.val != q.val) {
                return false;
            } else {
                p = p.next;
                q = q.next;
            }
        }
        return true;
    }

    public boolean isPalindrome2(ListNode head) {
        // 回文：栈解决； 入栈；
        Stack<Integer> stack = new Stack<>();
        ListNode p = head;
        while (p != null) {
            stack.push(p.val);
            p = p.next;
        }

        ListNode q = head;
        while (q != null) {
            if (q.val != stack.pop()) {
                return false;
            }
            q = q.next;
        }
        return true;
    }

    private ListNode reverseRightNode(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode newNode = null;
        ListNode p = head;
        while (p != null) {
            ListNode next = p.next;
            // 头插法
            p.next = newNode;
            newNode = p;
            p = next;
        }
        return newNode;
    }

    private ListNode findMiddleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        // 注意这里的结束边界条件
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Thread thread = Thread.currentThread();
                System.out.println("当前线程:" + thread.getName());
            }
        };
        Thread thread = new Thread(task);
        thread.setName("test-thread-1");
        // 守护线程
        thread.setDaemon(true);
        thread.start();
    }
}